package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.StrategyTheme;
import cn.wolfcode.luowowo.query.StrategyThemeQuery;
import cn.wolfcode.luowowo.repository.StrategyThemeRepository;
import cn.wolfcode.luowowo.service.IStrategyThemeService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
public class StrategyThemeServiceImpl implements IStrategyThemeService {

    @Autowired
    private StrategyThemeRepository repository;
    @Override
    public StrategyTheme get(String id) {
        Optional<StrategyTheme> optional = repository.findById(id);
        //如果数据库不是空的
        if (optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Autowired
    private MongoTemplate template;
    /**
     * 分页操作
     * @param qo 分页条件
     * @return
     */
    @Override
    public Page list(StrategyThemeQuery qo) {
        Query query = new Query();
        Page<StrategyTheme> page = DBHelper.query(template, StrategyTheme.class, query, qo.getPageable());
        return page;
    }

    @Override
    public void save(StrategyTheme strategyTheme) {
        if (!StringUtils.hasLength(strategyTheme.getId())){
            strategyTheme.setId(null);
            repository.save(strategyTheme);
        }else{
            Query query = new Query();
            query.addCriteria(Criteria.where("id").is(strategyTheme.getId()));
            DBHelper.update(template,query,strategyTheme,"destId","destName","state");
        }
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public void changeHotValue(String id, int hot) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("ishot",hot);
        template.updateMulti(query,update,StrategyTheme.class);
    }

    @Override
    public List<StrategyTheme> list() {
        return repository.findAll();
    }
}
